/**
 * 将css样式表大字符串转化为可以动态设置样式的数组
 * @param {string} cssStr css字符串（要求）         
    .container {
        width: 800px;
        height: 40px;
        border: 1px solid #333;
        margin-left: 30px;
    }
    !!!!!!!!!注意此处的【空行】是必须的!!!!!!!!!
    .container {
        width: 800px;
        height: 40px;
        border: 1px solid #333;
        margin-left: 30px;
    }

 * @returns 解析好的样式数组
    [
        {
            selector:".container",
            css:{
                width: "800px",
                height: "40px",
                border: "1px solid #333",
                marginLeft: "30px auto",
            }
        }
    ]
 */
function parseCss(cssStr) {
    const regSelector = /\s*(.+)\s*({[\s\S]+?})/i;
    const regDakuohao = /[{}]/;
    const reg3 = /-[a-z]/;

    const retArr = [];

    const arr = cssStr.split("\n\n");
    // console.log(arr);

    arr.forEach((str) => {
        // console.log(str);
        const selector = regSelector.exec(str)[1].trim();
        const css = regSelector.exec(str)[2].trim();

        const obj = {};
        obj.selector = selector;
        obj.css = {};

        // 处理css
        let ta = css.split(";");
        // console.log(ta);
        ta.forEach((s, i) => {
            s = s.replace(regDakuohao, "").trim();
            s = s.replace(reg3, function (s) {
                // "-c"
                return s[1].toUpperCase();
            });
            ta.splice(i, 1, s);
        });
        ta = ta.filter((s) => s != "");
        // console.log(ta);

        ta.forEach((item) => {
            // left: 10px
            let [key, value] = item.split(":");
            key = key.trim();
            value = value.trim();

            obj.css[key] = value;
        });

        // console.log(obj,"\n\n\n");
        retArr.push(obj);
    });

    return retArr;
}

/**
 * 为指定的DOM结构应用css样式
 * @param {HTMLElement} domRoot dom根节点
 * @param {string} cssStr 要为domRoot使用的css样式字符串
 */
function applyCss(domRoot, cssStr) {
    const styles = parseCss(cssStr);

    styles.forEach(
        ({ selector, css }) => {
            // 根据selector找出所有匹配的元素
            const elements = domRoot.querySelectorAll(selector);
            // console.log(selector, elements, "\n\n\n");

            /* 为所有的元素设置对应的css样式 */
            for (let i = 0; i < elements.length; i++) {
                const el = elements[i];

                /* 将css中的所有样式都设置给el */
                for (let attr in css) {
                    el.style[attr] = css[attr];
                }
            }
        }
    );
}
